package org.mybatis.generator.codegen.mybatis3.controller.elements;

import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import org.mybatis.generator.api.IntrospectedColumn;
import org.mybatis.generator.api.dom.OutputUtilities;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.Method;
import org.mybatis.generator.api.dom.java.Parameter;
import org.mybatis.generator.api.dom.java.TopLevelClass;

/**
 * controller 进入详情页方法
 *
 * @author tangdelong
 * 2015年5月25日
 */
public class DetailShowMethodControllerGenerator extends AbstractJavaControllerMethodGenerator {

	@Override
	public void addControllerElements(TopLevelClass topLevelClass) {
		FullyQualifiedJavaType model = new FullyQualifiedJavaType(introspectedTable.getBaseRecordType());
		
		Set<FullyQualifiedJavaType> importedTypes = new TreeSet<FullyQualifiedJavaType>();
		Method method = new Method();
		method.setVisibility(JavaVisibility.PUBLIC);
		method.setReturnType(new FullyQualifiedJavaType("org.springframework.web.servlet.ModelAndView"));
		method.setName(model.getInjectName()+"DetailShow");

		method.addAnnotation("@RequestMapping(\"/"+model.getInjectName()+"DetailShow\")");
		
		List<IntrospectedColumn> introspectedColumns = introspectedTable.getPrimaryKeyColumns();
		for (IntrospectedColumn introspectedColumn : introspectedColumns) {
			FullyQualifiedJavaType type = introspectedColumn.getFullyQualifiedJavaType();
			method.addParameter(new Parameter(type, "id"));
		}
		
		
		
		// 方法内容
		FullyQualifiedJavaType service = new FullyQualifiedJavaType(introspectedTable.getMyBatis3JavaServiceType());
		
		String jspTarget = "";
		if(context.getJavaJSPGeneratorConfiguration() != null){
			jspTarget = context.getJavaJSPGeneratorConfiguration().getTargetPackage();
		}
		method.addBodyLine("ModelAndView view = new ModelAndView"
				+ "(\"/"+jspTarget+"/"
				+introspectedTable.getFullyQualifiedTable().getDomainObjectName().toLowerCase()+"/"
				+OutputUtilities.removeSuffix(introspectedTable.getMyBatis3JSPDetailFileName())+"\");");
		method.addBodyLine(model.getShortName()+" "+model.getInjectName()+" = "+service.getInjectName()+"."+introspectedTable.getSelectByPrimaryKeyStatementId()+"(id);");
		method.addBodyLine("view.addObject(\""+model.getInjectName()+"\", "+model.getInjectName()+");");
		method.addBodyLine("return view;");

		// 注释
		context.getCommentGenerator().addGeneralMethodComment(method, introspectedTable, "进入详情页面");

		if (context.getPlugins().clientDeleteByPrimaryKeyMethodGenerated(method, topLevelClass, introspectedTable)) {
			topLevelClass.addImportedTypes(importedTypes);
			topLevelClass.addMethod(method);
		}


	}

}
